<?php
function createThumbs($pathToImages, $pathToThumbs, $thumbWidth) {
	// open the directory
	$dir = opendir ( $pathToImages );
	
	// loop through it, looking for any/all JPG files:
	while ( false !== ($fname = readdir ( $dir )) ) {
		// parse path for the extension
		$info = pathinfo ( $pathToImages . $fname );
		// continue only if this is a JPEG image
		if (strtolower ( $info ['extension'] ) == 'jpg') {
			echo "Creating thumbnail for {$fname} <br />";
			
			// load image and get image size
			$img = imagecreatefromjpeg ( "{$pathToImages}{$fname}" );
			$width = imagesx ( $img );
			$height = imagesy ( $img );
			
			$new_width = 0; $new_height = 0;
			
			// calculate thumbnail size
			if($width>$height){
				$new_height = $thumbWidth;
				$new_width = floor ( $width * ($thumbWidth / $height));
			}else{
				$new_width = $thumbWidth;
				$new_height = floor ( $height * ($thumbWidth / $width) );
			}
			
			// create a new temporary image
			$tmp_img = imagecreatetruecolor ( $new_width, $new_height );
			
			// copy and resize old image into new image
			imagecopyresized ( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
			
			// save thumbnail into a file
			checkDirectory($pathToThumbs);
			imagejpeg ( $tmp_img, "{$pathToThumbs}{$fname}" );
		}
	}
	// close the directory
	closedir ( $dir );
}

function checkDirectory($directory) {
	$flag = false;
	
	// check directory existing
	if (is_dir ( $directory )) {
		$flag = true;
	} else {
		// $this->log("not have directory");
		
		if (mkdir ( $directory )) {
			// $this->log("make directory complete");
			
			// ef : http://php.net/manual/en/function.chmod.php
			// Changes file mode
			// Read and write for owner, read for everybody else
			if (chmod ( $directory, 0777 )) {
				// $this->log("set permission complete");
				
				$flag = true;
			} else {
				// $this->log("set permission fail");
			} // if else
		} else {
			// $this->log("make directory fail");
		} // if else
	} // if else
	
	return $flag;
}// checkDirectory

//createThumbs("images/sampledata/Gallery/รูปคณะสงฆ์/","images/sampledata/Gallery/รูปคณะสงฆ์/thumbs/",100);

$galleryRootPath = 'images/sampledata/Gallery/';
$thumb100RootPath = 'images/thumbnail/100/Gallery/';
$thumb205RootPath = 'images/thumbnail/205/Gallery/';


$dir = opendir ( $galleryRootPath );
// print_r($dir);
while ( false !== ($fname = readdir ( $dir )) ) {
	
	if(is_dir($galleryRootPath.$fname) && $fname!=".." && $fname!="."){
		//echo $fname."<br />";
		//TODO: Create thumbnail each there dirs.
		createThumbs($galleryRootPath.$fname."/",$thumb100RootPath.$fname."/",100);
		createThumbs($galleryRootPath.$fname."/",$thumb205RootPath.$fname."/",205);
	}
	
}
closedir ( $dir );



